/*
 *  Licensed to PECATS under one or more contributor license agreements below:
 *  1. http://www.mozilla.org/MPL/MPL-1.1.html
 *  2. http://www.gnu.org/licenses/gpl-2.0.html
 *  3. http://www.gnu.org/licenses/lgpl-2.1.html
*/

/* **********************************************************
*  Class to clean old files from a directory
*  Name: Cleanup.java
*  Author: www.pecats.com
*  Date: Sep 15, 2008
************************************************************/

package com.pecats.batch.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.pecats.batch.data.ConfigData;

/**
 * Used to clean up old log files and output files from processedlogs and output directories
 */

public class Cleanup implements Runnable 
{

	File f1 = null;
	File f2 = null;
	int dircounter;
	int filecounter;

	File[] logdir = null;
	File[][] logfiles = new File[100][10];

	File[] outputdir = null;
	File[][] outputfiles = new File[100][10];


	public void run() 
	{
		
		f1 = new File(ConfigData.processedlogsdir);
		f2 = new File(ConfigData.outputdir);
		while(true)
		{		
			try
			{	
				if (f1.isDirectory() && f2.isDirectory())
				{
					logdir = f1.listFiles();	
					for (dircounter=0; dircounter < logdir.length; dircounter++)
					{
						// Get list of Files
						logfiles[dircounter] = logdir[dircounter].listFiles();	
						for (filecounter=0; filecounter < logfiles[dircounter].length; filecounter++)
						{
							if((System.currentTimeMillis() - logfiles[dircounter][filecounter].lastModified()) > 172800)
							{
								logfiles[dircounter][filecounter].delete();
							}
						}	
					}

					outputdir = f2.listFiles();	
					for (dircounter=0; dircounter < outputdir.length; dircounter++)
					{
						outputfiles[dircounter] = outputdir[dircounter].listFiles();	
						for (filecounter=0; filecounter < outputfiles[dircounter].length; filecounter++)
						{
							if((System.currentTimeMillis() - outputfiles[dircounter][filecounter].lastModified()) > 604800)
							{
								outputfiles[dircounter][filecounter].delete();
							}
						}
					}
				}
			}

			catch (Exception e)
			{
			}

		}
	
   	}	

}